package com.aiou.security.authentication.wechat;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author zyb
 */
public class WeChatCodeAuthenticationProvider implements AuthenticationProvider {


    private WeChatUserDetailsService userDetailsService;
    private String appId;
    private String appSecret;

    public WeChatCodeAuthenticationProvider(WeChatUserDetailsService userDetailsService, String appId, String appSecret) {
        this.userDetailsService = userDetailsService;
        this.appId = appId;
        this.appSecret = appSecret;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WeChatAuthenticationToken.class.isAssignableFrom(authentication);
    }

    /**
     * Authenticate user based on {@link WeChatAuthenticationToken}
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WeChatAuthenticationToken authenticationToken = (WeChatAuthenticationToken) authentication;

        UserDetails userDetails = userDetailsService.loadUserByCode((String) authenticationToken.getPrincipal(), appId, appSecret);

        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        WeChatAuthenticationToken weChatAuthenticationToken = new WeChatAuthenticationToken(userDetails, userDetails.getAuthorities());
        weChatAuthenticationToken.setDetails(authenticationToken.getDetails());
        return weChatAuthenticationToken;
    }

}